package com.lagou.handler;




import java.lang.reflect.InvocationTargetException;

import org.springframework.beans.BeansException;
import org.springframework.cglib.reflect.FastClass;
import org.springframework.cglib.reflect.FastMethod;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.lagou.service.RpcRequest;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * 自定义的业务处理器
 */
@Component
public class UserServiceHandler extends ChannelInboundHandlerAdapter implements ApplicationContextAware {

    private static ApplicationContext applicationContext;
    
    @Override
	public void setApplicationContext(ApplicationContext arg0) throws BeansException {
    	UserServiceHandler.applicationContext = arg0 ;
		
	}



    //当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        //注意:  客户端将来发送请求的时候会传递一个参数:  UserService#sayHello#are you ok
         //1.判断当前的请求是否符合规则
        /*if(msg.toString().startsWith("UserService")){
            //2.如果符合规则,调用实现类货到一个result
            UserServiceImpl service = new UserServiceImpl();
            String result = service.sayHello(msg.toString().substring(msg.toString().lastIndexOf("#")+1));
            //3.把调用实现类的方法获得的结果写到客户端
            ctx.writeAndFlush(result);
        }*/
    	System.err.println("channelRead:"+msg);
    	if (msg instanceof RpcRequest) {
    		RpcRequest rpcRequest = (RpcRequest) msg;
    		Object result = handler(rpcRequest);
            ctx.writeAndFlush(result);
		}


    }


	private Object handler(RpcRequest rpcRequest) throws ClassNotFoundException, InvocationTargetException {
		
		Class<?> clazz = Class.forName(rpcRequest.getClassName());
		if (null==applicationContext) {
			System.out.println("NPE err");
		}
        Object serviceBean = applicationContext.getBean(clazz);

        Class<?> serviceClass = serviceBean.getClass();

        String methodName = rpcRequest.getMethodName();

        Class<?>[] parameterTypes = rpcRequest.getParameterTypes();
        Object[] parameters = rpcRequest.getParameters();


        FastClass fastClass = FastClass.create(serviceClass);
        FastMethod fastMethod = fastClass.getMethod(methodName, parameterTypes);

        return fastMethod.invoke(serviceBean, parameters);
	}


	
}
